package com.shoulder.core.exception;


import com.shoulder.core.api.ApiResult;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.sql.SQLSyntaxErrorException;

@Slf4j
public class BizExceptionHandler {

    public ApiResult<Object> handleException(Exception ex) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        if (ex instanceof BizException) {
            log.error("全局异常:{},url = {}", ex.getMessage(), request.getRequestURI(), ex);
            return ApiResult.badRequest(null, ex.getMessage());
        }
        if (ex instanceof MethodArgumentNotValidException e) {
            BindingResult bindingResult = e.getBindingResult();
            String defaultMessage = bindingResult.getFieldErrors().get(0).getDefaultMessage();
            log.error("参数异常:{},url = {}", defaultMessage, request.getRequestURI(), ex);
            return ApiResult.badRequest(null, defaultMessage);
        }
        if (ex instanceof SQLSyntaxErrorException e) {
            log.error("SQL语句异常:{},url = {}", ex.getMessage(), request.getRequestURI(), ex);
            return ApiResult.badRequest(null, "SQL语句异常");
        }
        log.error("系统异常:{},url = {}", ex.getMessage(), request.getRequestURI(), ex);
        return ApiResult.badRequest(null, "系统异常,请联系管理员");
    }
}
